<script lang="ts" setup>
import { onMounted, reactive, ref, unref } from 'vue';

import { Select } from 'ant-design-vue';

import { getEnergyStationMarker } from '#/api';
import markerRed from '#/assets/poi-marker-red.png';
import { useScript } from '#/hooks/useScript';

const props = defineProps({
  width: {
    type: String,
    default: '100%',
  },
  height: {
    type: String,
    default: 'calc(100vh - 90px)',
  },
});
const wrapRef = ref<HTMLDivElement | null>(null);
const TMap = ref();
const state = reactive({
  gMap: null,
  marker: null,
  infoWindow: null, // 窗体对象
  cityActive: '110107', // 默认选择区域
  cityOptions: [
    {
      label: '北京市东城区',
      fullname: '东城区',
      value: '110101',
    },
    {
      label: '北京市西城区',
      fullname: '西城区',
      value: '110102',
    },

    {
      label: '北京市朝阳区',
      value: '110105',
      fullname: '朝阳区',
    },
    {
      label: '北京市丰台区',
      value: '110106',
      fullname: '丰台区',
    },
    {
      label: '北京市石景山区',
      value: '110107',
      fullname: '石景山区',
    },
    {
      label: '北京市海淀区',
      value: '110108',
      fullname: '海淀区',
    },
    {
      label: '北京市通州区',
      value: '110112',
      fullname: '通州区',
    },
  ],
  boilerRoomDatas: [], // 锅炉房
  Polygons: null,
});

// const key =2LVBZ-CIA63-YFS3E-OULYH-WCAKO-3BF7D
const TECENT_MAP_URL =
  'https://map.qq.com/api/gljs?v=1.exp&key=OB4BZ-D4W3U-B7VVO-4PJWW-6TKDJ-WPB77&libraries=service';
const { load } = useScript({ src: TECENT_MAP_URL });
const initMap = async () => {
  await load();
  setTimeout(() => {
    const wrapEl = unref(wrapRef);
    if (!wrapEl) return;
    TMap.value = (window as any).TMap;

    const center = new TMap.value.LatLng(39.908_802, 116.397_502); // 设置中心点坐标
    state.gMap = new TMap.value.Map(wrapEl, {
      zoom: 8, // 设置地图缩放级别
      // mapStyleId: 'style1',
      center,
    });
    initData()
  }, 100);
};

onMounted(() => {
  initMap();
});

// 添加marker事件
const addMarker = (TMap: any, boilerData: []) => {
  let markerArr = [];
  if (boilerData.length === 0) {
    markerArr = [];
    return;
  }
  boilerData.map((item, index) => {
    const { boilerName, LatLog } = item;
    markerArr.push({
      id: `marker${index}`,
      position: new TMap.LatLng(Number(LatLog[0]), Number(LatLog[1])),
      properties: {
        title: boilerName || '',
      },
      list: item,
    });
  });
  state.marker = new TMap.MultiMarker({
    id: `marker-layer`,
    map: state.gMap,
    styles: {
      marker: new TMap.MarkerStyle({
        width: 25,
        height: 35,
        anchor: { x: 16, y: 32 },
        src: markerRed,
      }),
    },
    geometries: markerArr,
  });

  initInfoWindow(); // 初始化信息窗体
  state.infoWindow.close();
  // 监听回调函数（非匿名函数）
  const eventClick = (evt) => {
    state.infoWindow.open();
    state.infoWindow.setPosition(evt.geometry.position);
    const content = formatContent(evt.geometry.list);
    state.infoWindow.setContent(content);
  };
  state.marker.on('click', eventClick);
};

/** 移除marker */
const removeMarker = () => {
  if (state.marker) {
    state.marker.setMap(null);
    state.marker = null;
  }
};

/** 初始化infoWindow*/
const initInfoWindow = () => {
  state.infoWindow = new TMap.value.InfoWindow({
    map: state.gMap,
    enableCustom:true,
    position: new TMap.value.LatLng(39.984_104, 116.307_503), // 设置信息框位置
    content: 'Hello World!', // 设置信息框内容
    offset: { x: -3, y: -35 },
  });
};

/** 格式化窗体内容 */
const formatContent = (list: any) => {
  // 北京京能热力股份有限公司(雍景四季东区锅炉房)热力生产和供应简化管理:9.9
  const content = `<div class="custom-info-card">
          <div class="info-card-head">
           <span>${list.companyName}</span>
          </div>
          <div class="info-card-subTitle">（${list.boilerName}）</div>
          <p>热力生产和供应简化管理</p>
          <p>蒸吨数：${list.value}</p>
        </div>`;
  return content;
};

/** 行政区域高亮 */
const highlight = () => {
  // 服务类库文档地址：https://lbs.qq.com/webApi/javascriptGL/glDoc/glDocService
  const district = new TMap.value.service.District({
    // 新建一个行政区划类
    polygon: 2, // 返回行政区划边界的类型
  });
  // 关键字搜索行政区划，110000 = 北京行政区划代码 110102东城区
  const cityCode = Number(state.cityActive);
  district.search({ keyword: cityCode }).then((result) => {
    if (!result && !result.result) return;
    console.error(result);
    // 获取省市区列表及其边界信息
    const paths = result.result[0][0].polygon;
    const location = result.result[0][0].location;
    state.gMap.setCenter(location);
    state.gMap.setZoom(12);

    state.Polygons = new TMap.value.MultiPolygon({
      map: state.gMap,
      styles: {
        polygon: new TMap.value.PolygonStyle({
          color: 'rgba(0,125,255,0.7)', // 面填充色
          showBorder: false, // 是否显示拔起面的边线
          borderColor: '#00FFFF', // 边线颜色
          borderWidth: 10,
        }),
      },
      geometries: [
        {
          paths,
        },
      ],
    });
  });
};

/** 根据行政区查询能源站 */
const getEnergyStation = async (cityName: string) => {
  const res = await getEnergyStationMarker({});
  debugger;
};

/**加载数据 */
const initData = () => {
  highlight();
  removeMarker();
  const boilerRoomDatas=[{companyName:'北京京能热力股份有限公司',boilerName:'雍景四季东区锅炉房',title:'热力生产和供应简化管理',value:'9.9',LatLog:[39.912002,116.229494]}]
  addMarker(TMap.value,boilerRoomDatas)
}

/** 切换城市区域 */
const handleCityChange = async(val: any) => {
  state.cityActive = val;
  if (state.Polygons) {
    state.Polygons.destroy();
  }
  highlight(Number(val));
  removeMarker();
  const boilerRoomDatas=[{companyName:'北京京能热力股份有限公司',boilerName:'雍景四季东区锅炉房',title:'热力生产和供应简化管理',value:'9.9',LatLog:[39.912002,116.229494]}]
  addMarker(TMap.value, boilerRoomDatas);
};
</script>

<template>
  <div class="home-container bg-card">
    <div ref="wrapRef" :style="{ height, width }"></div>
    <!-- <div class="search-card bg-card p-4">
      <label>选择区域：</label>
      <Select
        v-model:value="state.cityActive"
        style="width: 200px"
        :options="state.cityOptions"
        @change="handleCityChange"
      />
    </div> -->
  </div>
</template>

<style lang="less" scoped>
.home-container {
  position: relative;
}
.search-card {
  border-radius: 3px;
  position: absolute;
  left: 20px;
  top: 30px;
  z-index: 1000 !important;
}
.custom-info-card {
  padding: 10px;
  background-color: #fff; /* 白色背景 */
  border: 1px solid #0df1f1; /* 灰色边框 */
  border-radius: 5px; /* 圆角边框 */
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3); /* 阴影效果 */
}
.info-card-title {
    font-weight: bold;
}
</style>
